<script setup lang="ts">
import { onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import type { ModalProps } from 'ant-design-vue'
import { Button, Modal, Radio, message } from 'ant-design-vue'
import type { FormState as RoleFormState } from '~@/api/role/role'
import type { FormState } from '~@/api/list/user-role'
import { getRoleInfoApi } from '~@/api/role/role'
import { assignApi, getUserRoleListApi } from '~@/api/list/user-role'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  userId: {
    type: [String, Number],
    default: null,
  },
  username: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['close', 'success'])
const loading = ref(false)
const roles = ref<RoleFormState[]>([])
const selectedRoles = ref<string | number | null>(null)
const userRoles = ref<(string | number)[]>([])

// 获取用户已有角色
async function getUserRoles() {
  if (props.userId) {
    try {
      const { data } = await getUserRoleListApi(props.userId)
      userRoles.value = data?.map(item => item.roleId) || []
      // 设置默认选中
      selectedRoles.value = userRoles.value.length > 0 ? userRoles.value[0] : null
    }
    catch (error) {
      console.error('获取用户角色失败:', error)
      message.error('获取用户角色失败')
      userRoles.value = []
      selectedRoles.value = []
    }
  }
  else {
    userRoles.value = []
    selectedRoles.value = []
  }
}

// 获取角色列表
async function getRoles() {
  loading.value = true
  try {
    const { data } = await getRoleInfoApi(1, 100)
    roles.value = data.list || []
  }
  catch (error) {
    console.error('获取角色列表失败:', error)
    message.error('获取角色列表失败')
  }
  finally {
    loading.value = false
  }
}

// 提交角色绑定
async function handleSubmit() {
  loading.value = true
  try {
    // 确保参数类型正确
    const formState = {
      userId: props.userId !== null ? Number(props.userId) : null,
      roleId: selectedRoles.value !== null ? Number(selectedRoles.value) : null,
    }

    await assignApi(formState)

    message.success('角色绑定成功')
    emit('success')
    handleCancel()
  }
  catch (error) {
    console.error('角色绑定失败:', error)
    message.error('角色绑定失败')
  }
  finally {
    loading.value = false
  }
}

// 取消操作
function handleCancel() {
  emit('close')
}

// 当visible变化时，重新加载数据
async function handleVisibleChange(visible: boolean) {
  if (visible && props.userId) {
    await Promise.all([
      getRoles(),
      getUserRoles(),
    ])
  }
}

// 监听visible变化
function visibleWatcher() {
  if (props.visible) {
    handleVisibleChange(true)
  }
}

onMounted(() => {
  visibleWatcher()
})

// 监听props变化
const unwatch = watch(() => props.visible, (newVal) => {
  visibleWatcher()
})

// 清理函数
onBeforeUnmount(() => {
  unwatch()
})
</script>

<template>
  <Modal
    v-model:open="props.visible"
    title="绑定角色"
    width="500px"
    :loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <div style="padding: 16px 0;">
      <div style="margin-bottom: 16px;">
        <span>当前用户：</span>
        <span style="color: #1890ff;">{{ props.username }}</span>
      </div>
      <div style="max-height: 300px; overflow-y: auto;">
        <Radio.Group v-model:value="selectedRoles">
          <div v-for="role in roles" :key="role.roleId" style="margin-bottom: 8px;">
            <Radio :value="role.roleId">
              {{ role.roleName }}
            </Radio>
          </div>
        </Radio.Group>
        <div v-if="roles.length === 0 && !loading" style="text-align: center; color: #999; padding: 40px;">
          暂无角色数据
        </div>
      </div>
    </div>
  </Modal>
</template>

<style scoped>
/* 可以根据需要添加样式 */
</style>
